package com.linwankaifa.linwancunyi.ui.back;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.linwankaifa.linwancunyi.R;
import com.linwankaifa.linwancunyi.bean.PatientBean;
import com.linwankaifa.linwancunyi.ui.adapter.PatientAdapter;
import com.linwankaifa.linwancunyi.util.Data_whole;
import com.linwankaifa.linwancunyi.util.JsonTransformation;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class BackPatientList extends AppCompatActivity {
    List<PatientBean> patientBeanList;
    private ListView inflictlistView;
    private PatientAdapter adapter;
    private List<PatientBean> inflictlist;
    View.OnKeyListener onKey = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER
                        || keyCode == KeyEvent.KEYCODE_ENTER) {

                    inflictlist = new ArrayList<>();
                    PatientBean patientBeantest = new PatientBean();
                    Field[] fields = patientBeantest.getClass().getDeclaredFields();

                    for (PatientBean patientBean : patientBeanList) {
                        for (Field field : fields) {
                            try {
                                String name = field.getName();
                                name = field.getName().substring(0, 1).toUpperCase() + name.substring(1);
                                Method m = patientBean.getClass().getMethod("get" + name);
                                String value = String.valueOf(m.invoke(patientBean));
                                Log.e("name", String.valueOf(field.getName()));

                                Log.e("value", String.valueOf(value));
                                if (value != null && value.contains(((EditText) findViewById(R.id.patientlistsearch)).getText().toString())) {
                                    inflictlist.add(patientBean);
                                    break;
                                }
                            } catch (Exception e) {
                                continue;
                            }

                        }

                    }
                    adapter = new PatientAdapter(BackPatientList.this, R.layout.item_patient, inflictlist);
                    inflictlistView = (ListView) findViewById(R.id.ct_patient_list);
                    inflictlistView.setAdapter(adapter);

                    return true;
                }
            }
            return false;
        }
    };
    private EditText search_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_list);

        search_content = (EditText) findViewById(R.id.patientlistsearch);
        search_content.setOnKeyListener(onKey);

        OkHttpClient client = new OkHttpClient();
        final PatientBean patient = new PatientBean();
        Log.e("dynamic", JsonTransformation.objectToJson(patient));

        String url = getString(R.string.url)+"/back/getpatientlist";
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast toast = Toast.makeText(getApplicationContext(), "患者信息获取失败", Toast.LENGTH_SHORT);
                toast.show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 判断是否成功
                final String isSuccess = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isSuccess.equals("404")) {
                            Toast.makeText(getApplicationContext(), "该患者不存在", Toast.LENGTH_SHORT).show();
                        } else {
                            patientBeanList = JsonTransformation.jsonToList(isSuccess, PatientBean.class);
                            //  Log.e("BackPatientList", String.valueOf(patientBeanList.size()));

                            inflictlist = patientBeanList;
                            //Log.e("BackPatientList", String.valueOf(inflictlist.size()));
                            for (int i = 0; i < inflictlist.size(); i++) {
                                if (inflictlist.get(i).getPatientname() == null) {
                                    inflictlist.get(i).setPatientname("新用户");
                                }
                                if (inflictlist.get(i).getPetname() == null) {
                                    inflictlist.get(i).setPetname("");
                                }
                                if (inflictlist.get(i).getPatientage() == null) {
                                    inflictlist.get(i).setPatientage(20);
                                }
                                if (inflictlist.get(i).getPatientsex() == null) {
                                    inflictlist.get(i).setPatientsex("");
                                }
                                if (inflictlist.get(i).getPhone() == null) {
                                    inflictlist.get(i).setPhone("");
                                }
                                if (inflictlist.get(i).getBirthday() == null) {
                                    inflictlist.get(i).setBirthday("");
                                }
                            }
                            adapter = new PatientAdapter(BackPatientList.this, R.layout.item_patient, inflictlist);
                            inflictlistView = (ListView) findViewById(R.id.ct_patient_list);
                            inflictlistView.setAdapter(adapter);
                            inflictlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    PatientBean patient = inflictlist.get(position);
                                    Data_whole.setPatientBean(patient);
                                    //         Log.e("dynamic", patient.getAccountnumber());
                                    Intent intent = new Intent(BackPatientList.this, BackPatientInfo.class);
                                    startActivity(intent);
                                }
                            });
                        }
                    }
                });
            }
        });

    }

    public void back(View view) {
        this.finish();
    }

    public void search(View view) {
        inflictlist = new ArrayList<>();
        PatientBean patientBeantest = new PatientBean();
        Field[] fields = patientBeantest.getClass().getDeclaredFields();

        for (PatientBean patientBean : patientBeanList) {
            for (Field field : fields) {
                try {
                    String name = field.getName();
                    name = field.getName().substring(0, 1).toUpperCase() + name.substring(1);
                    Method m = patientBean.getClass().getMethod("get" + name);
                    String value = String.valueOf(m.invoke(patientBean));
                    Log.e("name", String.valueOf(field.getName()));

                    Log.e("value", String.valueOf(value));
                    if (value != null && value.contains(((EditText) findViewById(R.id.patientlistsearch)).getText().toString())) {
                        inflictlist.add(patientBean);
                        break;
                    }
                } catch (Exception e) {
                    continue;
                }

            }

        }
        adapter = new PatientAdapter(BackPatientList.this, R.layout.item_patient, inflictlist);
        inflictlistView = (ListView) findViewById(R.id.ct_patient_list);
        inflictlistView.setAdapter(adapter);
    }
}
